package com.sh.group;




import com.sh.bean.BankMarketing_my;
import com.sh.bean.Distance_My;
import com.sh.bean.MySample;

import java.util.*;

public class ParallelGroupKnnClassifier_My {
    private int k;
    private int processors;
    private boolean b;
    private List<BankMarketing_my> train;

    public ParallelGroupKnnClassifier_My(int k, int processors, boolean b, List<BankMarketing_my> train) {
        this.k = k;
        this.processors = processors;
        this.b = b;
        this.train = train;
    }


    public String classify(MySample example){
        Distance_My[] distanceMies = new Distance_My[train.size()];  // 存储每个样本与当前样本的距离
        int length = train.size()/processors;
        int startIndex = 0;
        int endIndex = length;

        ArrayList<Thread> list = new ArrayList<>();
        for (int i = 0; i < processors; i++) {
            GroupDistanceTask_My groupDistanceTaskMy = new GroupDistanceTask_My(distanceMies, startIndex, endIndex, train, example);
            Thread t = new Thread(groupDistanceTaskMy);
            t.start();
            list.add(t);
            startIndex = endIndex;
            endIndex = i==processors-2? train.size():  endIndex+length;
        }

        for (Thread thread : list) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException("线程调度异常");
            }
        }

        if (b){
            Arrays.parallelSort(distanceMies);
        }else {
            Arrays.sort(distanceMies);
        }

        HashMap<String, Integer> mapK = new HashMap<>();   // 目标值， 次数
        for (int i = 0; i < k; i++) {
            int index = distanceMies[i].getIndex();
            String tag = train.get(index).getTag();   // 获取标签
            if ( mapK.containsKey(tag)){
                mapK.put(tag, mapK.get(tag)+1);
            }else {
                mapK.put(tag, 1);
            }
        }


        String maxTag = null;
        int temp = 0;
        for (Map.Entry<String, Integer> one : mapK.entrySet()) {
            if ( one.getKey()!=null && one.getValue()>=temp){
                maxTag = one.getKey();
                temp = one.getValue();
            }
        }

        return maxTag;

    }
}
